<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h2>传递json给服务器</h2>
    <button class="get">获取图书</button>
    <button class="add">新增图书</button>
    <button class="edit">修改图书</button>
    <button class="delete">删除图书</button>
    <script>
      /*
        参数是一个对象
          url 地址+get的参数(如果有的话)
          method
          data:{} 通过请求体传递的数据 写到这里.对象的格式
         
      */
      function myAxios(opt){
        const {method,url,data}=opt
        return new Promise((resolve, reject) => {
          const xhr = new XMLHttpRequest()
        // 2.设置请求的 方法 和地址
        xhr.open(method, url)
        xhr.setRequestHeader('content-type', 'application/json')
        // 3.注册回调函数 服务器响应内容回来之后触发
        xhr.addEventListener('load', function () {
          // response 响应
          // console.log(xhr.response)
          resolve(xhr.response)
        })
        // 4.发送请求
        xhr.send(JSON.stringify(data))
        })
       }

      
      document.querySelector('.get').onclick=()=>{
        myAxios({
        method:'get',
        url:'http://ajax-api.itheima.net/api/books',
       }).then(res=>{
        console.log(JSON.parse(res));
       })
      }
      document.querySelector('.add').onclick=()=>{
        myAxios({
        method:'post',
        url:'http://ajax-api.itheima.net/api/books',
        data: {
          bookname:'盗墓笔记全套',
          author:'南派三叔',
          publisher:'杭州西冷印社',
        }
       }).then(res=>{
        console.log(res);
       })
      }
      document.querySelector('.edit').onclick=()=>{
        myAxios({
        method:'put',
        url:'http://ajax-api.itheima.net/api/books/218',
        data: {
          bookname:'盗墓笔记之秦岭神树',
          author:'倒斗南派三叔',
          publisher:'杭州西冷印社',
        }
       }).then(res=>{
        console.log(res);
       })
      }

      document.querySelector('.delete').onclick=()=>{
        myAxios({
        method:'delete',
        url:'http://ajax-api.itheima.net/api/books/207',
       
       }).then(res=>{
        console.log(res);
       })
      }

      
    </script>
  </body>
</html>
